package org.testis.testdriver.translation;

import java.util.HashMap;

/**
 *
 * @author barisergun
 */
public class AtofUseMapTranslateAction extends AtofValueTranslateAction {

    private HashMap<String, String> m_usedatamap;

    public AtofUseMapTranslateAction(HashMap<String, String> usedatamap) {
        m_usedatamap = usedatamap;
    }

    @Override
    public String operateRequest(String dataPointer) {
        if (m_usedatamap != null) {
            String parseVal = AtofTranslationConstants.USEMAP_CONSTANT;
            String endVal = "#";
            int beginIndex = dataPointer.indexOf(parseVal);
            while (beginIndex != -1) {

                int keyBeginIndex = beginIndex + parseVal.length();

                int keyEndIndex;

                if (dataPointer.indexOf(endVal,
                        keyBeginIndex) != -1) {
                    keyEndIndex = dataPointer.indexOf(endVal,
                            keyBeginIndex) + 1;
                } else if (dataPointer.indexOf(" ",
                        keyBeginIndex) != -1) {
                    keyEndIndex = dataPointer.indexOf(" ",
                            keyBeginIndex);
                } else if (dataPointer.indexOf('\0',
                        keyBeginIndex) != -1) {
                    keyEndIndex = dataPointer.indexOf('\0',
                            keyBeginIndex);
                } else {
                    keyEndIndex = dataPointer.length();
                }

                String keyPointer = dataPointer.substring(
                        keyBeginIndex,
                        keyEndIndex);
                keyPointer = keyPointer.replace(endVal,
                        "");

                String toBeReplaced = dataPointer.substring(beginIndex,
                        keyEndIndex);

                String replacing = m_usedatamap.get(keyPointer);

                if (replacing == null) {
                    throw new UnidentifiedTranslationException(
                            "No value found for UseMap Key: " + keyPointer);
                }

                dataPointer = dataPointer.replace(toBeReplaced,
                        replacing);

                beginIndex = dataPointer.indexOf(parseVal,
                        0);

            }
        }

        return dataPointer;

    }
}
